<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="定时发送播报" name="first">
          <!-- <h1 class="title">定时发送播报</h1> -->
          <!-- 新增 -->
          <!-- <el-button type="success" @click="sipSend">播放计划</el-button> -->

          <!-- 发送语音-->
          <div class="dashboard-container">
            <!-- <div class="dashboard-text">name: {{ name }}</div> -->
            <el-card class="box-card">
              <!-- 表单 -->
              <div class="timeBox">
                <el-form
                  :inline="true"
                  v-loading="loading"
                  ref="form"
                  :model="form"
                  :rules="Rules"
                  label-width="100px"
                >
                  <!-- 播报模式 -->
                  <el-form-item label="播报模式">
                    <template>
                      <el-radio
                        v-model="form.radio"
                        label="1"
                        @input="radioChange"
                        >定时单次发送</el-radio
                      >
                      <el-radio v-model="form.radio" label="2"
                        >定时发送</el-radio
                      >
                    </template>
                  </el-form-item>
                  <!-- 广播播日期 -->
                  <el-form-item label="日期" prop="time">
                    <el-date-picker
                      v-model="form.time"
                      type="daterange"
                      align="right"
                      unlink-panels
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :picker-options="pickerOptions"
                    >
                    </el-date-picker>
                  </el-form-item>
                  <!-- 广播播时间 -->
                  <el-form-item
                    label="时间"
                    prop="clock"
                    v-if="form.radio === '2'"
                  >
                    <el-time-picker
                      is-range
                      v-model="form.clock"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                    >
                    </el-time-picker>
                  </el-form-item>
                  <el-form-item
                    label="时间"
                    prop="clock"
                    v-if="form.radio === '1'"
                  >
                    <el-time-picker
                      v-model="form.clock"
                      placeholder="任意时间点"
                    >
                    </el-time-picker>
                  </el-form-item>
                  <!-- 播报间隔 -->
                  <el-form-item
                    label="播报间隔"
                    v-if="form.radio === '2'"
                    prop="interval"
                  >
                    <el-input
                      v-model="form.interval"
                      style="width: 80px"
                    ></el-input
                    >分钟
                  </el-form-item>
                  <!-- 播报间隔 -->
                  <el-form-item label="播报间隔" v-if="form.radio === '1'">
                    <el-input
                      v-model="form.interval"
                      disabled
                      style="width: 80px"
                    ></el-input
                    >分钟
                  </el-form-item>
                  <!-- 播报次数-->
                  <!-- <el-form-item
                    label="播报次数"
                    prop="broadcast_times"
                    v-if="activeName === 'first'"
                  >
                    <el-input
                      v-model="form.times"
                      style="width: 80px"
                    ></el-input
                    >次数
                  </el-form-item> -->
                  <!-- 基站ID -->
                  <el-form-item label="基站" prop="checkedList">
                    <template>
                      <el-cascader
                        v-model="form.checkedList"
                        @change="checkedFn"
                        :options="options"
                        :props="props"
                        collapse-tags
                        clearable
                      ></el-cascader>
                    </template>
                  </el-form-item>

                  <!-- 播报内容 -->
                  <el-form-item label="播报语音" prop="content">
                    <div class="comtent">
                      <el-input
                        v-model="form.content"
                        :disabled="true"
                      ></el-input>
                      <el-button
                        type="primary"
                        icon="el-icon-s-order"
                        @click="audioTextDlalog"
                      ></el-button>
                    </div>
                  </el-form-item>
                  <el-form-item style="margin-left: 50px">
                    <el-button type="primary" @click="getSip('form')"
                      >确定</el-button
                    >
                    <el-button icon="el-icon-refresh-left" @click="reset"
                      >重置</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </el-card>
          </div>
          <!-- 表格 -->
          <el-table :data="sipTable" border style="width: 100%">
            <el-table-column prop="call_name" label="广播频道" width="120">
              <template slot-scope="props">
                <el-popover
                  placement="top-start"
                  title="广播频道"
                  width="200"
                  trigger="hover"
                  :content="props.row.call_name"
                >
                  <div slot="reference">
                    {{ props.row.call_name.slice(0, 20) }}
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="content" label="播报内容">
              <template slot-scope="props">
                <el-popover
                  placement="top-start"
                  title="播报内容"
                  width="200"
                  trigger="hover"
                  :content="props.row.content"
                >
                  <div slot="reference">
                    {{ props.row.content.slice(0, 30) }}
                  </div>
                </el-popover>
              </template>
            </el-table-column> -->

            <el-table-column label="开始时间" width="140">
              <template slot-scope="scope">
                {{
                  $moment(scope.row.create_start_time * 1000).format(
                    "YYYY-MM-DD/HH:mm"
                  )
                }}
              </template>
            </el-table-column>

            <el-table-column label="结束时间" width="140">
              <template slot-scope="scope">
                {{
                  scope.row.create_end_time === null
                    ? "无"
                    : $moment(scope.row.create_end_time * 1000).format(
                        "YYYY-MM-DD/HH:mm"
                      )
                }}
              </template>
            </el-table-column>

            <el-table-column prop="" label="播报次数" width="120">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.played_times }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="" label="播报间隔" width="120">
              <template slot-scope="scope">
                <span>
                  {{
                    scope.row.interval === null
                      ? "0"
                      : scope.row.interval + "分钟"
                  }}
                </span>
              </template>
            </el-table-column>

            <el-table-column prop="" label="广播状态" width="120">
              <template slot-scope="scope">
                <span
                  class="el-icon-success"
                  style="color: #13ce66"
                  v-if="scope.row.status === 1"
                ></span>
                <span
                  class="el-icon-warning"
                  style="color: #fbdc3c"
                  v-if="scope.row.status === 0"
                ></span>
                <span
                  class="el-icon-circle-close"
                  style="color: #ff4949"
                  v-if="scope.row.status === -2"
                ></span>
                <span>
                  {{
                    scope.row.status === 1
                      ? "已播放"
                      : scope.row.status === 0
                      ? "未播放"
                      : scope.row.status === -2
                      ? "出错"
                      : scope.row.status === -1
                      ? "取消广播"
                      : ""
                  }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作">
              <template slot="header" slot-scope="scope">
                <div class="excel-btn">
                  <el-button
                    type="success"
                    style="margin-left: 10px"
                    @click="exportToExcel"
                    >导出</el-button
                  >
                </div>
              </template>
              <template slot-scope="scope">
                <!-- <el-button @click="sendDialog(scope.row)" size="mini"
              >发送</el-button
            > -->
                <!-- <el-button @click="sipStop(scope.row)" size="mini">{{
                  scope.row.stop === 0 ? "停止" : "启动"
                }}</el-button> -->
                <!-- <el-button @click="edit(scope.row)" size="mini">编辑</el-button> -->
                <el-button
                  @click="WxHf(scope.row)"
                  size="mini"
                  type="success"
                  v-if="scope.row.status === -1"
                  >恢复广播</el-button
                >
                <el-button
                  @click="wxQuit(scope.row)"
                  size="mini"
                  type="danger"
                  v-if="scope.row.status === 0"
                  >取消播放广播</el-button
                >
                <el-button @click="del(scope.row)" size="mini" type="danger"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <el-pagination
            layout="prev, pager, next"
            :page-count="paging.total"
            @current-change="page_change"
          >
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <VoiceText
      :dialogVisible="voiceTextDialogVisible"
      @update:dialogVisible="handleDialogVisibleChange"
      @upload="upload"
    ></VoiceText>
  </div>
</template>

<script>
import VoiceText from "../sipComponents/index.vue";
import {
  getSipData,
  getTimingTable,
  sipDelete,
  sipUpdate,
  sipStaus,
  ajaxInitiator,
  sipLoopSend,
  siptimingSend,
  getTimingSendTable,
  getTimingCycleTable,
  timingSendQuit,
  sipUser,
} from "@/api/sip";

import { Message } from "element-ui";
import { getcheck } from "../encapsulation";
import * as XLSX from "xlsx";

export default {
  components: {
    VoiceText,
  },
  data() {
    return {
      // sip数据表格
      sipTable: [],
      sipForm: {},
      CycleAndSenddialogVisible: false,
      //音频对话框
      voiceTextDialogVisible: false,
      // 加载
      loading: false,
      //基站全选
      checked: false,
      //频道全选
      channel_checked: false,
      //请求服务器sip发起地数据
      ajaxInitiatorName: [],
      //基站数据
      callData: [],
      //频道数据
      channelData: [],
      // 分页
      paging: {
        pag: 1,
        limit: 10,
        total: 100,
      },
      props: { multiple: true },
      options: [],

      form: {
        sip_ip: "", //sip地址
        sip_port: "", //sip端口
        user_id: "", //发起id
        password: "", //密码
        call_id: "", //接收id
        content: "", //内容
        start_time_date: "", //播报起始时间
        end_time_date: "", //播报结束时间
        time: "", //时间需要转换参数
        interval: "", //间隔时间
        // times: "", //播放次数
        clock: "", //时钟
        path: "", //播放语音路径
        radio: "2",
        checkedList: [],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      activeName: "first",
      ajaxInitiatorName: [],
      // 定时参数必填规则
      Rules: {
        clock: [{ required: true, message: "日期不能为空", trigger: "blur" }],
        time: [{ required: true, message: "时间不能为空", trigger: "blur" }],
        call_id: [
          { required: true, message: "播报ID不能为空", trigger: "blur" },
        ],
        interval: [
          { required: true, message: "播报间隔不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "播报语音不能为空", trigger: "blur" },
        ],
        checkedList: [
          { required: true, message: "请选择基站", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.sipInit(1, "first");
    this.sipSend();
    this.sipOpen();
  },
  methods: {
    async sipInit(page, activeName) {
      let name = JSON.parse(localStorage.getItem("HSKJ-username"));
      // this.sipTable = data;
      //循环播报
      if (activeName === "first") {
        const ajaxInitiatorData = await ajaxInitiator({ userChanne: name });
        this.ajaxInitiatorName = ajaxInitiatorData.data.meta.data;
        //获取发起地ids 提供给表格使用
        let call_ids = ajaxInitiatorData.data.meta.data.map((item) => {
          return item.Initiator_id;
        });
        //表格数据
        const res = await getTimingSendTable({ pag: page || 1, call_ids });
        this.sipTable = res.data.data.rows;
        // this.sipTable = data;
        this.paging.total = res.data.data.total;
      }
      if (activeName === "second") {
        const res = await getTimingCycleTable({ pag: page || 1 });
        const ajaxInitiatorData = await ajaxInitiator({ userChanne: name });
        this.sipTable = res.data.data.rows;
        // this.sipTable = data;
        this.paging.total = res.data.data.total;
        this.ajaxInitiatorName = ajaxInitiatorData.data.meta.data;
      }

      //循环匹配发起地
      this.sipTable.forEach((item) => {
        let calliIdName = [];
        this.ajaxInitiatorName.forEach((elemnt) => {
          if (Number(item.call_id) === elemnt.Initiator_id) {
            item.call_name = elemnt.Initiator_name;
          }

          let calliIdList = item.call_id.split("@");

          if (calliIdList.length >= 2) {
            calliIdList.forEach((val) => {
              if (Number(val) === elemnt.Initiator_id) {
                calliIdName.push(elemnt.Initiator_name);
              }
            });
            item.call_name = calliIdName.join("@");
          }
        });
      });
    },
    async sipSend() {
      let result = await sipUser();

      let sipuserData = result.data.data.rows[0];

      this.form.user_id = String(sipuserData.user_id);
      this.form.password = sipuserData.password;
    },
    //发送广播
    getSip(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid === false) {
          return;
        } else {
          let startZhDate;
          let endZhDate;
          let startZhTime;
          let endZhTime;
          let ajaxStartTime;
          let ajaxEndTime;
          if (this.form.radio === "2") {
            //处理日期格式
            startZhDate = this.formatDateNOUTC(1, this.form.time[0]);
            endZhDate = this.formatDateNOUTC(1, this.form.time[1]);
            startZhTime = this.formatDateNOUTC(2, this.form.clock[0]);
            endZhTime = this.formatDateNOUTC(2, this.form.clock[1]);

            //发请求所需时间戳
            ajaxStartTime =
              new Date(`${startZhDate} ${startZhTime}`).getTime() / 1000;
            ajaxEndTime =
              new Date(`${endZhDate} ${endZhTime}`).getTime() / 1000;
          } else {
            startZhDate = this.formatDateNOUTC(1, this.form.time[0]);
            startZhTime = this.formatDateNOUTC(2, this.form.clock);
            ajaxStartTime =
              new Date(`${startZhDate} ${startZhTime}`).getTime() / 1000;
          }

          // console.log(457, {
          //   sip_ip: this.form.sip_ip,
          //   sip_port: this.form.sip_port,
          //   user_id: this.form.user_id,
          //   call_id: this.form.call_id,
          //   password: "",
          //   content: this.form.content,
          //   create_start_time: String(ajaxStartTime),
          //   create_end_time: String(ajaxEndTime),
          //   speed: "1.0",
          //   interval: this.form.interval,
          //   path: this.form.path,
          // });

          if (this.form.radio === "2") {
            let res = await siptimingSend({
              sip_ip: this.form.sip_ip,
              sip_port: this.form.sip_port,
              user_id: this.form.user_id,
              call_id: this.form.call_id,
              password: this.form.password,
              create_start_time: String(ajaxStartTime),
              create_end_time: String(ajaxEndTime),
              speed: "1.0",
              interval: this.form.interval,
              name: this.form.content,
              mode: this.form.radio,
            });

            if (res.data.status_code === 0) {
              this.$message.success("添加成功");
              this.sipInit(1, this.activeName);
            }
          } else {
            let res = await siptimingSend({
              sip_ip: this.form.sip_ip,
              sip_port: this.form.sip_port,
              user_id: this.form.user_id,
              call_id: this.form.call_id,
              password: this.form.password,
              create_start_time: String(ajaxStartTime),
              create_end_time: "",
              interval: "",
              speed: "1.0",
              name: this.form.content,
              mode: this.form.radio,
            });

            if (res.data.status_code === 0) {
              this.$message.success("添加成功");
              this.sipInit(1, this.activeName);
            }
          }
        }
      });
    },
    //打开音频对话框
    audioTextDlalog() {
      this.voiceTextDialogVisible = true;
    },
    handleDialogVisibleChange(newValue) {
      this.voiceTextDialogVisible = newValue;
    },
    // 导出excel
    exportToExcel() {
      // 直接使用XLSX的内置导出方法
      const ws = XLSX.utils.json_to_sheet(
        this.sipTable.map((item) => ({
          接收地: item.call_name,
          播报内容: item.content,
          开始时间: this.$moment(item.create_start_time * 1000).format(
            "YYYY-MM-DD/HH:mm"
          ),
          结束时间: this.$moment(item.create_end_time * 1000).format(
            "YYYY-MM-DD/HH:mm"
          ),
          播报次数: item.played_times + "次",
          播报间隔: item.interval / 60 + "分钟",
          广播状态:
            item.status === 0 ? "未播放" : item.status === 1 ? "已播放" : "",
        }))
      );

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "定时表格");

      // 直接导出文件（不需要file-saver）
      XLSX.writeFile(wb, "定时表格.xlsx");
    },
    async sipOpen() {
      let name = JSON.parse(localStorage.getItem("HSKJ-username"));
      const res = await ajaxInitiator({ userChanne: name });
      this.ajaxInitiatorName = res.data.meta.data;
      // // 处理成element ui 使用的格式

      this.ajaxInitiatorName.forEach((item) => {
        item.label = item.Initiator_name;
        item.value = {
          ip: item.ip_gateway,
          port: item.port,
          callId: item.Initiator_id,
        };
      });

      let CH14_list = this.ajaxInitiatorName.filter((item) => {
        return item.channel === "CH14";
      });
      let CH16_list = this.ajaxInitiatorName.filter((item) => {
        return item.channel === "CH16";
      });
      let CH0_list = this.ajaxInitiatorName.filter((item) => {
        return item.channel === "CH0";
      });
      this.options = [
        {
          value: "CH14",
          label: "CH14",
          children: CH14_list,
        },
        {
          value: "CH16",
          label: "CH16",
          children: CH16_list,
        },
        {
          value: "CH0",
          label: "CH0",
          children: CH0_list,
        },
      ];
    },
    // 分页
    page_change(data) {
      this.sipInit(data, "first");
    },
    //处理日期格式
    formatDateNOUTC(type, date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      if (type === 1) {
        return `${year}-${month}-${day}`;
      }
      if (type === 2) {
        return `${hours}:${minutes}:${seconds}`;
      }
    },
    async del(data) {
      await sipDelete({ id: String(data.id), activeName: this.activeName });
      Message.success("删除成功");
      this.sipInit(1, this.activeName);
    },
    // // 基站全选
    checkedFn(data) {
      this.form.checkedList = data;
      //提取网关ip
      this.form.sip_ip = this.form.checkedList.map((item) => item[1].ip);
      this.form.sip_port = this.form.checkedList.map((item) => item[1].port);
      this.form.call_id = this.form.checkedList.map((item) =>
        String(item[1].callId)
      );

      if (this.form.sip_ip.length >= 2) {
        this.form.sip_ip = this.form.sip_ip.join("@");
      } else {
        this.form.sip_ip = this.form.sip_ip[0];
      }

      if (this.form.sip_port.length >= 2) {
        this.form.sip_port = this.form.sip_port.join("@");
      } else {
        this.form.sip_port = this.form.sip_port[0];
      }

      if (this.form.call_id.length >= 2) {
        this.form.call_id = this.form.call_id.join("@");
      } else {
        this.form.call_id = this.form.call_id[0];
      }
    },
    //播报模式清空播间隔
    radioChange() {
      this.form.interval = "";
    },
    close() {
      this.CycleAndSenddialogVisible = false;
    },
    // 基站选择值
    sipChange(data) {
      //多选
      // 收集选择之对象
      this.form.sip_obj = data;
      //提取数据
      this.form.sip_id_list = this.form.sip_obj.map((item) => {
        return item.value;
      });
      this.form.sip_ip_list = this.form.sip_obj.map((item) => {
        return item.ip;
      });
    },
    //频道选择值
    channel_Change(data) {
      //多选
      // this.form.call_id = data
      // 收集选择之对象
      this.form.channel_obj = data;
      //提取数据
      this.form.channel_id_list = this.form.channel_obj.map((item) => {
        return item.value;
      });

      this.form.channel_ip_list = this.form.channel_obj.map((item) => {
        return item.ip;
      });
    },
    reset() {
      this.sipSend();
      // (this.form = {
      //   sip_ip: "", //sip地址
      //   sip_port: "", //sip端口
      //   password: "", //密码
      //   call_id: "", //接收id
      //   content: "", //内容
      //   start_time_date: "", //播报起始时间
      //   end_time_date: "", //播报结束时间
      //   time: "", //时间需要转换参数
      //   interval: "", //间隔时间
      //   clock: "", //时钟
      //   path: "", //播放语音路径
      //   radio: "2",
      // }),
      this.form.sip_ip = "";
      this.form.sip_port = "";
      this.form.call_id = "";
      this.form.content = "";
      this.form.start_time_date = "";
      this.form.end_time_date = "";
      this.form.time = "";
      this.form.interval = "";
      this.form.clock = "";
      this.form.path = "";
      this.form.radio = "2";
      this.form.checkedList = [];
    },
    handleClick(tab, event) {
      this.sipInit(1, this.activeName);
    },
    //接收音频子组件返回值
    upload(newValue) {
      this.form.content = newValue.name;
    },
    async wxQuit(data) {
      let res = await timingSendQuit({ id: data.id, status: "-1" });
      if (res.data.meta.code === 200) {
        this.$message.success("取消广播成功");
        this.sipInit(1, this.activeName);
      }
    },

    async WxHf(data) {
      let res = await timingSendQuit({ id: data.id, status: "0" });
      if (res.data.meta.code === 200) {
        this.$message.success("恢复广播成功");
        this.sipInit(1, this.activeName);
      }
    },
  },
};
</script>

<style>
.title {
  text-align: center;
}
.comtent {
  display: flex;
}
.dashboard-container {
  margin-bottom: 41px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.excel-btn {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: right;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
